package tools

import (
	"reflect"
	"unicode"
	"unicode/utf8"
	"unsafe"
)

func BytesToString(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}

func StringToBytes(s string) []byte {
	sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
	bh := reflect.SliceHeader{Data: sh.Data, Len: sh.Len, Cap: sh.Len}
	return *(*[]byte)(unsafe.Pointer(&bh))
}

func SafeTruncate(size int, input string) string {
	if len(input) > size {
		set := []*unicode.RangeTable{unicode.Letter, unicode.Punct, unicode.White_Space, unicode.Han}
		for size > 0 {
			r, _ := utf8.DecodeLastRuneInString(input[:size])
			if unicode.IsOneOf(set, r) {
				break
			}
			size--
		}
		return input[:size]
	}
	return input
}
